package icu.cocoon.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import icu.cocoon.dao.base.BaseService;
import icu.cocoon.system.entity.Org;
import icu.cocoon.system.entity.RoleMenu;
import icu.cocoon.system.mapper.OrgMapper;
import icu.cocoon.system.service.OrgService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.ArrayList;
import java.util.List;
import org.ehcache.core.util.CollectionUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Cocoon
 * @since 2020-06-11
 */
@Service
public class OrgServiceImpl extends BaseService<OrgMapper, Org> implements OrgService {

  @Override
  public List<Org> findByName(String name) {
    return getMapper().selectList(new QueryWrapper<Org>().lambda().eq(Org::getName, name));
  }

  @Override
  public List<Org> findByParentId(Long parentId) {
    return getMapper().selectList(new QueryWrapper<Org>().lambda().eq(Org::getParentId, parentId));
  }

  @Override
  public List<Org> findAllChildren(Long parentId) {
    List<Org> result = new ArrayList<>();
    subOrgAll(parentId, result);
    return result;
  }

  private void subOrgAll(Long parentId, List<Org> resultOrgList) {
    List<Org> orgList = findByParentId(parentId);
    if (CollectionUtils.isEmpty(orgList)) {
      return;
    }
    resultOrgList.addAll(orgList);
    for (Org org : orgList) {
      subOrgAll(org.getParentId(), resultOrgList);
    }
  }
}
